package com.ruoyi.store.xxljob;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.store.mapper.TbStoreMapper;
import com.ruoyi.store.template.MsgTemplate;
import com.ruoyi.store.template.WXTemplate;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class PushMessage {

    @Autowired
    private TbStoreMapper tbStoreMapper;

    private String APPID="wx01cb0b0967195727";

    private String APPSECRET="6116762897ac990ee6dc300e07cc60d9";

    private String pushMessageTemplateId="v-t2lXSnURvTcxYzrObAfkf1cLmBtn0Kw4RbH8Zc4S8";

    @XxlJob(value = "pushMessageTask")
    public void pushMessageJob() throws IOException {
        List<String> sikgaekIds = tbStoreMapper.selectSikgaekIds();
        String tokenUrl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+APPID+"&secret="+APPSECRET;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(tokenUrl);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        String json = EntityUtils.toString(response.getEntity());
        ObjectMapper objectMapper = new ObjectMapper();
        Map map = objectMapper.readValue(json, Map.class);
        String accessToken = (String) map.get("access_token");
        String url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+accessToken;
        WXTemplate wxTemplate = new WXTemplate();
        wxTemplate.setTemplate_id(pushMessageTemplateId);
        MsgTemplate msgTemplate = new MsgTemplate();
        msgTemplate.setValue("来签到喽");
        msgTemplate.setColor("#ffba00");
        Map dataMap=new HashMap();
        dataMap.put("message",msgTemplate);
        wxTemplate.setData(dataMap);
        for (String sikgaekId : sikgaekIds) {
            wxTemplate.setTouser(sikgaekId);
            String requestJson = objectMapper.writeValueAsString(wxTemplate);
            System.out.println(requestJson);
            HttpPost httpPost = new HttpPost(url);
            //HttpEntity是一个接口   StringEntity是HttpEntity接口的实现类的子类
            httpPost.setEntity(new StringEntity(requestJson,"UTF-8"));
            httpClient.execute(httpPost);
        }
    }
}
